const server = Bun.serve<{ username: string }>({
    async fetch(req, server) {
        const url = new URL(req.url);
        let userId=url.searchParams.get('userId')
        if (url.pathname === "/chat") {
            console.log(`upgrade!`);
            const username = 'zhangsan';
            const success = server.upgrade(req, {data: {userId}});
            return success
                ? undefined
                : new Response("WebSocket upgrade error", {status: 400});
        }

        return new Response("Hello world");
    },
    websocket: {
        open(ws) {
            console.log('客户端成功连接')
            console.log('用户id',ws.data.userId)
            //用户连接后，用户id注册一个通道，其他人就可以通过这个通道
            //给该用户发消息
            ws.subscribe(ws.data.userId);
            //server.publish("the-group-chat", 'msg');
        },
        message(ws, message) {
            console.log('收到前端消息：',message)
            let msg=JSON.parse(message)
            console.log(msg)
            if (msg.fn=='createRoom'){//执行加入qq群逻辑
                console.log('后端创建游戏房间成功')
                msg.msg='创建游戏房间成功'
                server.publish(msg.from, JSON.stringify(msg));
                return
            }
            if (msg.fn=='addGroup'){//执行加入qq群逻辑
                ws.subscribe('qq1');
                server.publish(msg.from, '成功加入qq群');
                return
            }
            if (msg.fn=='sendGroup'){//群聊逻辑
                server.publish('qq1', msg.msg);
                return
            }
            //服务端再给前端发消息
            //然后服务器把ie的消息转发给360
            server.publish(msg.to, msg.data);
        },
        close(ws) {
            const msg = `${ws.data.username} has left the chat`;
            ws.unsubscribe("the-group-chat");
            server.publish("the-group-chat", msg);
        },
    },
});

console.log(`Listening on ${server.hostname}:${server.port}`);